<template>
  <div class="posts-audit-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span class="title">帖子审核管理</span>
          <div class="header-actions">
            <el-button type="danger" @click="confirmDeleteRejected" :loading="deletingRejected">清理所有被拒绝帖子</el-button>
            <el-button type="primary" @click="fetchPendingPosts">刷新数据</el-button>
          </div>
        </div>
      </template>
      
      <!-- 帖子列表 -->
      <el-table
        v-loading="loading"
        :data="pendingPosts"
        style="width: 100%"
        border
      >
        <el-table-column prop="id" label="ID" width="80" />
        <el-table-column prop="title" label="标题" min-width="180" show-overflow-tooltip />
        <el-table-column prop="content" label="内容" min-width="250" show-overflow-tooltip>
          <template #default="scope">
            <div v-html="formatContent(scope.row.content)"></div>
          </template>
        </el-table-column>
        <el-table-column label="发布者" width="120">
          <template #default="scope">
            {{ scope.row.userNickname || (scope.row.user ? scope.row.user.nickname : '未知用户') }}
          </template>
        </el-table-column>
        <el-table-column label="分类" width="100">
          <template #default="scope">
            {{ getPostTypeText(scope.row.type) }}
          </template>
        </el-table-column>
        <el-table-column prop="createdAt" label="发布时间" width="180">
          <template #default="scope">
            {{ formatDate(scope.row.createdAt) }}
          </template>
        </el-table-column>
        <el-table-column label="附件" width="100">
          <template #default="scope">
            <el-button 
              v-if="scope.row.images && scope.row.images.length > 0" 
              type="primary" 
              link 
              @click="viewAttachments(scope.row.images)"
            >
              查看图片
            </el-button>
            <span v-else>无图片</span>
          </template>
        </el-table-column>
        <el-table-column label="操作" width="240" fixed="right">
          <template #default="scope">
            <el-button type="info" size="small" @click="viewPostDetail(scope.row.id)">详情</el-button>
            <el-button type="success" size="small" @click="approvePost(scope.row)">通过</el-button>
            <el-button type="danger" size="small" @click="openRejectDialog(scope.row)">拒绝</el-button>
          </template>
        </el-table-column>
      </el-table>
      
      <!-- 分页 -->
      <div class="pagination-container">
        <el-pagination
          v-model:current-page="currentPage"
          v-model:page-size="pageSize"
          :page-sizes="[10, 20, 50, 100]"
          layout="total, sizes, prev, pager, next, jumper"
          :total="total"
          @size-change="handleSizeChange"
          @current-change="handleCurrentChange"
        />
      </div>
    </el-card>
    
    <!-- 附件查看对话框 -->
    <el-dialog
      v-model="attachmentsDialogVisible"
      title="帖子附件"
      width="60%"
    >
      <div class="attachments-container">
        <div v-for="(attachment, index) in currentAttachments" :key="index" class="attachment-item">
          <div v-if="isImage(attachment)">
            <img :src="attachment" class="attachment-image" />
          </div>
          <div v-else class="file-attachment">
            <el-icon><Document /></el-icon>
            <a :href="attachment" target="_blank">{{ `附件${index + 1}` }}</a>
          </div>
        </div>
      </div>
    </el-dialog>
    
    <!-- 拒绝原因对话框 -->
    <el-dialog
      v-model="rejectDialogVisible"
      title="拒绝帖子"
      width="40%"
    >
      <el-form :model="rejectForm" label-width="80px">
        <el-form-item label="拒绝原因" required>
          <el-input
            v-model="rejectForm.reason"
            type="textarea"
            :rows="4"
            placeholder="请输入拒绝原因，将通知给用户"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <span class="dialog-footer">
          <el-button @click="rejectDialogVisible = false">取消</el-button>
          <el-button type="danger" @click="rejectPost" :loading="submitting">确认拒绝</el-button>
        </span>
      </template>
    </el-dialog>
    
    <!-- 帖子详情对话框 -->
    <el-dialog
      v-model="postDetailDialogVisible"
      title="帖子详情"
      width="70%"
    >
      <div v-loading="loadingDetail">
        <div v-if="currentPostDetail" class="post-detail">
          <h2 class="post-title">{{ currentPostDetail.title }}</h2>
          <div class="post-meta">
            <span>作者: {{ currentPostDetail.userNickname || (currentPostDetail.user ? currentPostDetail.user.nickname : '未知用户') }}</span>
            <span>分类: {{ getPostTypeText(currentPostDetail.type) }}</span>
            <span>发布时间: {{ formatDate(currentPostDetail.createdAt) }}</span>
            <span>状态: {{ getStatusText(currentPostDetail.status) }}</span>
          </div>
          <div class="post-content" v-html="currentPostDetail.content"></div>
          
          <div v-if="currentPostDetail.images && currentPostDetail.images.length > 0" class="post-images">
            <h3>帖子图片</h3>
            <div class="images-container">
              <div v-for="(image, index) in currentPostDetail.images" :key="index" class="image-item">
                <img :src="image" class="detail-image" />
              </div>
            </div>
          </div>
        </div>
        <div v-else-if="!loadingDetail" class="no-detail">
          无法加载帖子详情
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import { Document } from '@element-plus/icons-vue'
import axios from 'axios'

// 数据状态
const loading = ref(false)
const submitting = ref(false)
const pendingPosts = ref([])
const total = ref(0)
const currentPage = ref(1)
const pageSize = ref(10)
const deletingRejected = ref(false)

// 附件查看相关
const attachmentsDialogVisible = ref(false)
const currentAttachments = ref([])

// 拒绝对话框相关
const rejectDialogVisible = ref(false)
const rejectForm = ref({
  reason: '',
  postId: null
})

// 帖子详情相关
const postDetailDialogVisible = ref(false)
const currentPostDetail = ref(null)
const loadingDetail = ref(false)

// 获取待审核帖子
const fetchPendingPosts = async () => {
  loading.value = true
  try {
    const response = await axios.get('http://localhost:3000/api/forum/admin/posts/pending', {
      params: {
        page: currentPage.value,
        pageSize: pageSize.value
      },
      headers: {
        Authorization: `Bearer ${localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).token : ''}`
      }
    })
    
    // 处理响应数据，适配后端返回的posts字段
    if (response.data.posts && Array.isArray(response.data.posts)) {
      pendingPosts.value = response.data.posts
      total.value = response.data.total || response.data.posts.length
    } else if (Array.isArray(response.data)) {
      pendingPosts.value = response.data
      total.value = response.data.length
    } else {
      pendingPosts.value = []
      total.value = 0
    }
  } catch (error) {
    ElMessage.error(`获取待审核帖子失败: ${error.message || '未知错误'}`)
  } finally {
    loading.value = false
  }
}

// 查看帖子详情
const viewPostDetail = (postId) => {
  loadingDetail.value = true
  currentPostDetail.value = null
  postDetailDialogVisible.value = true
  
  try {
    // 从已有的帖子列表中查找对应ID的帖子
    const post = pendingPosts.value.find(p => p.id === postId)
    if (post) {
      currentPostDetail.value = post
    } else {
      ElMessage.warning('未找到该帖子详情')
    }
  } catch (error) {
    ElMessage.error(`获取帖子详情失败: ${error.message || '未知错误'}`)
  } finally {
    loadingDetail.value = false
  }
}

// 删除所有被拒绝的帖子
const deleteRejectedPosts = async () => {
  deletingRejected.value = true
  try {
    await axios.post('http://localhost:3000/api/forum/admin/posts/delete-rejected', {}, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).token : ''}`
      }
    })
    ElMessage.success('已成功清理所有被拒绝的帖子')
    fetchPendingPosts()
  } catch (error) {
    ElMessage.error(`清理被拒绝帖子失败: ${error.message || '未知错误'}`)
  } finally {
    deletingRejected.value = false
  }
}

// 确认删除被拒绝的帖子
const confirmDeleteRejected = () => {
  ElMessageBox.confirm(
    '确定要删除所有被拒绝的帖子吗？此操作不可恢复！',
    '警告',
    {
      confirmButtonText: '确定删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    deleteRejectedPosts()
  }).catch(() => {})
}

// 获取状态文本
const getStatusText = (status) => {
  const statusMap = {
    pending: '待审核',
    approved: '已通过',
    rejected: '已拒绝'
  }
  return statusMap[status] || status
}

// 获取帖子类型文本
const getPostTypeText = (type) => {
  const typeMap = {
    general: '综合',
    technical: '技术',
    question: '问答',
    share: '分享'
  }
  return typeMap[type] || type
}

// 分页处理
const handleSizeChange = (size) => {
  pageSize.value = size
  fetchPendingPosts()
}

const handleCurrentChange = (page) => {
  currentPage.value = page
  fetchPendingPosts()
}

// 格式化日期
const formatDate = (dateString) => {
  if (!dateString) return ''
  const date = new Date(dateString)
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit'
  })
}

// 格式化内容（截取前100个字符）
const formatContent = (content) => {
  if (!content) return ''
  const plainText = content.replace(/<[^>]+>/g, '')
  return plainText.length > 100 ? plainText.substring(0, 100) + '...' : plainText
}

// 查看附件
const viewAttachments = (images) => {
  currentAttachments.value = images
  attachmentsDialogVisible.value = true
}

// 判断是否为图片
const isImage = (url) => {
  if (!url) return false
  return /\.(jpg|jpeg|png|gif|webp)$/i.test(url)
}

// 通过帖子
const approvePost = (post) => {
  ElMessageBox.confirm(
    `确定通过帖子"${post.title}"吗？`,
    '确认操作',
    {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'success'
    }
  ).then(() => {
    reviewPost(post.id, true)
  }).catch(() => {})
}

// 打开拒绝对话框
const openRejectDialog = (post) => {
  rejectForm.value = {
    reason: '',
    postId: post.id
  }
  rejectDialogVisible.value = true
}

// 拒绝帖子
const rejectPost = async () => {
  if (!rejectForm.value.reason.trim()) {
    ElMessage.warning('请输入拒绝原因')
    return
  }
  
  submitting.value = true
  try {
    await reviewPost(rejectForm.value.postId, false, rejectForm.value.reason)
    rejectDialogVisible.value = false
  } finally {
    submitting.value = false
  }
}

// 审核帖子
const reviewPost = async (postId, approved, rejectReason) => {
  submitting.value = true
  try {
    await axios.patch(`http://localhost:3000/api/forum/admin/posts/${postId}/review`, {
      approved,
      rejectReason
    }, {
      headers: {
        Authorization: `Bearer ${localStorage.getItem('user') ? JSON.parse(localStorage.getItem('user')).token : ''}`
      }
    })
    
    ElMessage.success(approved ? '帖子已通过审核' : '帖子已拒绝')
    // 刷新列表
    fetchPendingPosts()
  } catch (error) {
    ElMessage.error(`审核操作失败: ${error.message || '未知错误'}`)
  } finally {
    submitting.value = false
  }
}

// 页面加载时获取数据
onMounted(() => {
  fetchPendingPosts()
})
</script>

<style scoped>
.posts-audit-container {
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.header-actions {
  display: flex;
  gap: 10px;
}

.title {
  font-size: 18px;
  font-weight: bold;
}

.pagination-container {
  margin-top: 20px;
  display: flex;
  justify-content: flex-end;
}

.attachments-container {
  display: flex;
  flex-wrap: wrap;
  gap: 15px;
}

.attachment-item {
  width: 200px;
  margin-bottom: 15px;
}

.attachment-image {
  max-width: 100%;
  max-height: 200px;
  border-radius: 4px;
  border: 1px solid #eee;
}

.file-attachment {
  display: flex;
  align-items: center;
  gap: 8px;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 4px;
}

.file-attachment a {
  color: #409eff;
  text-decoration: none;
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}

/* 帖子详情样式 */
.post-detail {
  padding: 10px;
}

.post-title {
  margin-bottom: 15px;
  color: #303133;
}

.post-meta {
  display: flex;
  gap: 20px;
  margin-bottom: 20px;
  color: #606266;
  font-size: 14px;
}

.post-content {
  margin-bottom: 20px;
  line-height: 1.6;
  white-space: pre-wrap;
}

.post-images {
  margin-top: 20px;
}

.images-container {
  display: flex;
  flex-wrap: wrap;
  gap: 10px;
}

.image-item {
  width: 200px;
  margin-bottom: 10px;
}

.detail-image {
  max-width: 100%;
  border-radius: 4px;
  border: 1px solid #eee;
}

.no-detail {
  text-align: center;
  padding: 30px;
  color: #909399;
}
</style>